<template>
  <div class="upload-file"
       v-show="!isCollapsed"
       :style="{paddingLeft:`${(itemData.path.length - 1) * 20}px`}">
    <div class="tree-node-heading">
      <div class="icon-expand" @click="handleToggleExpandStatus">
        <i class="el-icon-caret-right" v-if="isChildrenCollapsed"></i>
        <i class="el-icon-caret-bottom" v-else></i>
      </div>
      <div class="directory">{{ itemData.directory }}</div>
      <div v-if="!isRootNode" class="actions">
        <el-button type="text" :icon="toggleFileListCfg.icon"
                   @click="toggleFileList">{{ toggleFileListCfg.label }}</el-button>
<!--        <el-upload
          multiple
          :action="uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :file-list="fileList"
          :limit="limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :headers="headers"
          class="upload-file-uploader"
          ref="fileUpload"
        >
          <el-tooltip class="item" effect="dark"
                      :content="`请上传大小不超过${fileSize}MB格式为${fileType.join('/')}的文件`"
                      placement="top-start">
            &lt;!&ndash; 上传按钮 &ndash;&gt;
            <el-button type="text" icon="el-icon-upload2">选取文件</el-button>
          </el-tooltip>
        </el-upload>
        &lt;!&ndash; 上传按钮 &ndash;&gt;
        <el-button type="text" icon="el-icon-camera" @click="openCamera">拍照上传</el-button>-->
      </div>
    </div>

    <!-- 文件列表 -->
    <div style="padding-left: 30px;">
      <el-table v-if="!isRootNode" v-show="showFileList"
                :data="fileList" border style="width: 100%" size="small">
        <el-table-column prop="name" label="文件">
          <template slot-scope="scope">
            <i class="el-icon-document"></i>
            <span style="margin-left: 6px;">{{ scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作" width="200px">
          <template v-slot:default="scope">
            <el-button type="text" size="small" @click="handleDownload(scope.row, scope.$index)">下载</el-button>
<!--            <el-button type="text" size="small" @click="handleDelete(scope.$index)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <AmCameraModal ref="AmCameraModalRef"
                   @confirm="handleCameraSubmit"/>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import AmCameraModal from "@/components/AmComp/AmCameraModal.vue";
import dayjs from "dayjs";
import {isEmpty} from "lodash";
import {delAmArchive} from "../../../api/am/amArchive";

export default {
  name: "AmDirectoryViewRow",
  components: {AmCameraModal},
  props: {
    collapsedIds: Array,
    //
    itemData: Object,
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    fileTypes: Array,
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [
        'doc', 'docx',
        'xls', 'xlsx',
        'ppt',  'pptx',
        'txt', 'pdf',
        'png', 'jpg',
        'bmp', 'webp',
        'gif', 'jpeg'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    isShowFileLIst: Boolean
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/minio/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      showFileList: false,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
          this.showFileList = !isEmpty(this.fileList);
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    isRootNode() {
      return this.itemData.path.length === 1;
    },
    isChildrenCollapsed() {
      return this.collapsedIds.includes(this.itemData.id)
    },
    isCollapsed() {
      return !isEmpty(this.itemData.path
        .filter(item => item !== this.itemData.id)
        .filter(item => this.collapsedIds.includes(item)))
    },
    toggleFileListCfg() {
      return this.showFileList ? {
        label: '隐藏文件列表',
        icon: 'el-icon-zoom-out',
      } : {
        label: '显示文件列表',
        icon: 'el-icon-zoom-in',
      }
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    handleToggleExpandStatus() {
      this.$emit('toggleExpand', this.itemData)
    },
    toggleFileList() {
      this.showFileList = !this.showFileList;
    },
    openCamera() {
      this.$refs.AmCameraModalRef.open()
    },
    handleCameraSubmit(blob) {
      const file = new window.File(
        [blob],
        `camera_${dayjs().valueOf()}.png`,
        {type: blob.type}
      )
      this.$refs.fileUpload.handleStart(file);
      this.$refs.fileUpload.submit();
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      const { data: resFile } = res;
      if (res.code === 200) {
        this.uploadList.push(resFile);
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
      }
      this.uploadedSuccessfully();
    },
    handleDownload(file) {
      window.open(`${file.downloadUrl}`, '_blank');
    },
    // 删除文件
    handleDelete(row, index) {
      delAmArchive(row.fileId).then(res => {
        this.fileList.splice(index, 1);
        this.$emit('input', this.fileList);
      })
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit('input', this.fileList);
        this.$modal.closeLoading();
        if(!this.showFileList) {
          this.toggleFileList();
        }
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file{
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px #EEE solid;
}
.upload-file-uploader {
  //margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}


.tree-node-heading{
  display: flex;
  align-items: center;
  height: 36px;
  margin-bottom: 6px;
  cursor: pointer;
  .icon-expand{
    width: 20px;
    height: 20px;
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .directory{
    flex: 1;
    font-size: 15px;
    font-weight: 800;
  }
  .actions{
    display: flex;
    gap: 10px;
  }
}
</style>
